import 'package:flutter/material.dart';
import 'dart:convert';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:photo_pipeline/photo_pipeline.dart';
import '../constants/colors.dart';
import '../constants/spacing.dart';
import '../constants/dimensions.dart';
import '../constants/text_styles.dart';
import '../mock_data/mock_data.dart';
import '../providers/pipeline_media_providers.dart';

/// 图片列表页面
///
/// 以列表形式展示图片，支持选择和操作
class PhotoListScreen extends ConsumerStatefulWidget {
  const PhotoListScreen({super.key});

  @override
  ConsumerState<PhotoListScreen> createState() => _PhotoListScreenState();
}

class _PhotoListScreenState extends ConsumerState<PhotoListScreen> {
  @override
  void initState() {
    super.initState();
  }

  Widget _buildPagedList() {
    final params = const PaginationParams(page: 1, pageSize: 20);
    final pageAsync = ref.watch(mediaPageProvider(params));
    return pageAsync.when(
      data: (page) {
        final items = page.data;
        if (items.isEmpty) {
          return _buildEmptyState();
        }
        return ListView.builder(
          padding: const EdgeInsets.symmetric(horizontal: AppSpacing.md),
          itemCount: items.length,
          itemBuilder: (context, index) {
            final e = items[index];
            return Padding(
              padding: const EdgeInsets.only(bottom: AppSpacing.sm),
              child: _buildListItem(
                e,
                index,
              ),
            );
          },
        );
      },
      loading: () => const Center(child: CircularProgressIndicator()),
      error: (err, _) => Center(
        child: Text('加载失败：$err', style: AppTextStyles.body2),
      ),
    );
  }

  // 直接使用 EnhancedFileInfo 进行展示
  Widget _buildEmptyState() {
    return Center(
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          const Icon(Icons.image_not_supported, color: AppColors.textSecondary),
          const SizedBox(height: 8),
          Text(
            '暂无照片',
            style: AppTextStyles.body2.copyWith(color: AppColors.textSecondary),
          ),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    final stats = MockData.uploadStats;

    return Scaffold(
      backgroundColor: AppColors.background,
      body: SafeArea(
        child: Stack(
          children: [
            // 主内容区
            Column(
              children: [
                // 顶部导航栏
                _buildTopNavBar(context),

                // 中间内容区（白色半透明背景）
                Expanded(
                  child: Container(
                    decoration: const BoxDecoration(
                      gradient: LinearGradient(
                        begin: Alignment.topCenter,
                        end: Alignment.bottomCenter,
                        colors: [
                          Color(0x1FFFFFFF), // rgba(255, 255, 255, 0.12)
                          Color(0x0FFFFFFF), // rgba(255, 255, 255, 0.06)
                        ],
                      ),
                      borderRadius: BorderRadius.only(
                        topLeft: Radius.circular(16),
                        topRight: Radius.circular(16),
                      ),
                    ),
                    child: Column(
                      children: [
                        const SizedBox(height: AppSpacing.md),

                        // 第一行：全部统计 + 缓存信息 + 搜索图标
                        _buildTopRow(stats),

                        const SizedBox(height: AppSpacing.xl),

                        // 第二行：状态Tab栏
                        _buildStatusTabs(stats),

                        const SizedBox(height: AppSpacing.md),

                        // 第三行：筛选/排序/时间轴/全选
                        _buildActionButtons(),

                        const SizedBox(height: AppSpacing.md),

                        // 列表区域（接入分页 Provider 示例）
                        Expanded(
                          child: _buildPagedList(),
                        ),
                      ],
                    ),
                  ),
                ),
              ],
            ),

            // 底部渐变遮罩
            Positioned(
              left: 0,
              right: 0,
              bottom: 0,
              child: Container(
                height: 94,
                decoration: const BoxDecoration(
                  gradient: LinearGradient(
                    begin: Alignment.topCenter,
                    end: Alignment.bottomCenter,
                    colors: [
                      Color(0x00000000),
                      Color(0xFF000000),
                    ],
                  ),
                ),
              ),
            ),

            // 底部导入按钮
            Positioned(
              right: 16,
              bottom: 94,
              child: _buildImportButton(context),
            ),

            // 底部操作栏
            Positioned(
              left: 43,
              right: 43,
              bottom: 22,
              child: _buildBottomActionBar(),
            ),
          ],
        ),
      ),
    );
  }

  /// 构建顶部导航栏
  Widget _buildTopNavBar(BuildContext context) {
    return Container(
      height: 44,
      padding: const EdgeInsets.symmetric(horizontal: AppSpacing.md),
      child: Row(
        children: [
          // 返回按钮
          Container(
            width: 32,
            height: 32,
            decoration: BoxDecoration(
              color: AppColors.cardBackground,
              borderRadius: BorderRadius.circular(60),
            ),
            child: IconButton(
              padding: EdgeInsets.zero,
              icon: const Icon(
                Icons.arrow_back_ios_new,
                size: 16,
                color: AppColors.textPrimary,
              ),
              onPressed: () => Navigator.pop(context),
            ),
          ),

          const SizedBox(width: AppSpacing.sm),

          // 中间占位
          Container(
            padding: const EdgeInsets.symmetric(
              horizontal: 8,
              vertical: 2,
            ),
            decoration: BoxDecoration(
              color: AppColors.cardBackground,
              borderRadius: BorderRadius.circular(20),
            ),
            height: 32,
          ),
        ],
      ),
    );
  }

  /// 构建第一行：全部统计 + 缓存信息 + 搜索图标
  Widget _buildTopRow(stats) {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: AppSpacing.md),
      child: Row(
        children: [
          // 左侧：全部统计
          Text(
            '全部',
            style: AppTextStyles.heading3.copyWith(
              color: AppColors.textPrimary,
            ),
          ),
          const SizedBox(width: 4),
          Container(
            padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 6),
            decoration: BoxDecoration(
              color: AppColors.cardBackground,
              borderRadius: BorderRadius.circular(8),
            ),
            child: Text(
              '${stats.allCount}',
              style: AppTextStyles.caption.copyWith(
                fontWeight: FontWeight.w500,
                color: AppColors.textPrimary,
              ),
            ),
          ),

          const Spacer(),

          // 右侧：缓存信息
          Container(
            padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 8),
            decoration: BoxDecoration(
              color: AppColors.cardBackground,
              borderRadius: BorderRadius.circular(20),
            ),
            child: Row(
              mainAxisSize: MainAxisSize.min,
              children: [
                Text(
                  '100MB',
                  style: AppTextStyles.body2.copyWith(
                    color: AppColors.textPrimary,
                  ),
                ),
                const SizedBox(width: 10),
                const Icon(
                  Icons.delete_outline,
                  size: 16,
                  color: AppColors.textPrimary,
                ),
              ],
            ),
          ),

          const SizedBox(width: 12),

          // 搜索图标
          Container(
            width: 28,
            height: 28,
            decoration: BoxDecoration(
              color: AppColors.cardBackground,
              borderRadius: BorderRadius.circular(6),
            ),
            child: const Icon(
              Icons.search,
              size: 20,
              color: AppColors.textPrimary,
            ),
          ),
        ],
      ),
    );
  }

  /// 构建状态Tab栏
  Widget _buildStatusTabs(stats) {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: AppSpacing.md),
      child: Row(
        children: [
          Flexible(
            child: _buildTabItem(
              '待挑',
              stats.pendingCount,
              isActive: true,
            ),
          ),
          const SizedBox(width: 12),
          Flexible(child: _buildTabItem('上传中', stats.uploadingCount)),
          const SizedBox(width: 12),
          Flexible(child: _buildTabItem('已上传', stats.uploadedCount)),
          const SizedBox(width: 12),
          Flexible(child: _buildTabItem('失败', stats.failedCount)),
        ],
      ),
    );
  }

  /// 构建单个Tab项
  Widget _buildTabItem(String label, int count, {bool isActive = false}) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 6),
      decoration: BoxDecoration(
        color: isActive
            ? const Color(0x33FFFFFF) // rgba(255, 255, 255, 0.2)
            : const Color(0x0DFFFFFF), // rgba(255, 255, 255, 0.05)
        borderRadius: BorderRadius.circular(AppDimensions.radiusXs),
      ),
      child: Center(
        child: Text(
          '$label $count',
          style: AppTextStyles.caption.copyWith(
            color: AppColors.textSecondary,
          ),
          textAlign: TextAlign.center,
          overflow: TextOverflow.ellipsis,
          maxLines: 1,
        ),
      ),
    );
  }

  /// 构建操作按钮行（筛选/排序/时间轴/全选）
  Widget _buildActionButtons() {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: AppSpacing.md),
      child: Row(
        children: [
          // 时间轴按钮（高亮）
          Container(
            padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 6),
            decoration: BoxDecoration(
              color: AppColors.cardBackground,
              borderRadius: BorderRadius.circular(14),
            ),
            child: Row(
              mainAxisSize: MainAxisSize.min,
              children: [
                Text(
                  '时间轴',
                  style: AppTextStyles.body2.copyWith(
                    color: AppColors.textPrimary,
                  ),
                ),
                const SizedBox(width: 4),
                const Icon(
                  Icons.keyboard_arrow_down,
                  size: 16,
                  color: AppColors.textPrimary,
                ),
              ],
            ),
          ),

          const Spacer(),

          // 排序（半透明）
          Opacity(
            opacity: 0.4,
            child: _buildIconTextButton(Icons.sort, '排序'),
          ),

          const SizedBox(width: 8),

          // 筛选（半透明）
          Opacity(
            opacity: 0.4,
            child: _buildIconTextButton(Icons.filter_list, '筛选'),
          ),

          const SizedBox(width: 8),

          // 全选（半透明）
          Opacity(
            opacity: 0.4,
            child: _buildIconTextButton(Icons.check_box_outline_blank, '全选'),
          ),
        ],
      ),
    );
  }

  /// 构建图标+文本按钮
  Widget _buildIconTextButton(IconData icon, String text) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 6),
      child: Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          Icon(
            icon,
            size: 16,
            color: AppColors.textPrimary,
          ),
          const SizedBox(width: 4),
          Text(
            text,
            style: AppTextStyles.body2.copyWith(
              color: AppColors.textPrimary,
            ),
          ),
        ],
      ),
    );
  }

  /// 构建列表项（使用 EnhancedFileInfo 展示）
  Widget _buildListItem(EnhancedFileInfo item, int index) {
    final file = item.fileInfo;
    final fileName = file.name ?? 'IMG_${file.id}';
    return Container(
      height: 64,
      decoration: BoxDecoration(
        color: const Color(0x0AFFFFFF), // rgba(255, 255, 255, 0.04)
        borderRadius: BorderRadius.circular(12),
      ),
      padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
      child: Row(
        children: [
          // 照片缩略图（base64）
          Container(
            width: 48,
            height: 48,
            decoration: BoxDecoration(
              color: AppColors.cardBackground,
              borderRadius: BorderRadius.circular(8),
            ),
            clipBehavior: Clip.antiAlias,
            child: _buildThumbnail(item),
          ),

          const SizedBox(width: 12),

          // 照片信息
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Text(
                  fileName,
                  style: AppTextStyles.body1.copyWith(
                    color: AppColors.textPrimary,
                  ),
                ),
                const SizedBox(height: 4),
                Text(
                  '${(file.size ?? 0) ~/ (1024 * 1024)}MB • ${file.mimeType ?? ''}',
                  style: AppTextStyles.caption.copyWith(
                    color: AppColors.textSecondary,
                  ),
                ),
              ],
            ),
          ),

          const Icon(Icons.chevron_right, color: AppColors.textSecondary),
        ],
      ),
    );
  }

  Widget _buildThumbnail(EnhancedFileInfo item) {
    final thumb = item.fileInfo.thumbnailPath;
    if (thumb == null || thumb.isEmpty) {
      return const Icon(
        Icons.image,
        size: 24,
        color: AppColors.textSecondary,
      );
    }
    try {
      // 兼容 data URI 或纯 base64 字符串
      final data = thumb.contains(',') ? thumb.split(',').last : thumb;
      final bytes = base64Decode(data);
      return Image.memory(
        bytes,
        fit: BoxFit.cover,
      );
    } catch (_) {
      return const Icon(
        Icons.broken_image_outlined,
        size: 24,
        color: AppColors.textSecondary,
      );
    }
  }

  /// 构建导入按钮
  Widget _buildImportButton(BuildContext context) {
    return GestureDetector(
      onTap: () {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(
            content: Text('导入功能'),
            backgroundColor: AppColors.primary,
          ),
        );
      },
      child: Container(
        padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
        decoration: BoxDecoration(
          color: AppColors.cardBackground,
          borderRadius: BorderRadius.circular(24),
          boxShadow: const [
            BoxShadow(
              color: Color(0x0FFFFFFF),
              offset: Offset(0, 2),
              blurRadius: 4,
              blurStyle: BlurStyle.inner,
            ),
            BoxShadow(
              color: Color(0x14FFFFFF),
              offset: Offset(0, -2),
              blurRadius: 4,
              blurStyle: BlurStyle.inner,
            ),
          ],
        ),
        child: Row(
          mainAxisSize: MainAxisSize.min,
          children: [
            const Icon(
              Icons.download,
              size: 20,
              color: AppColors.textPrimary,
            ),
            const SizedBox(width: 2),
            Text(
              '导入',
              style: AppTextStyles.body2.copyWith(
                color: AppColors.textPrimary,
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// 构建底部操作栏
  Widget _buildBottomActionBar() {
    return Container(
      height: 56,
      padding: const EdgeInsets.all(4),
      decoration: BoxDecoration(
        color: const Color(0x05FFFFFF), // rgba(255, 255, 255, 0.02)
        borderRadius: BorderRadius.circular(32),
        boxShadow: const [
          BoxShadow(
            color: Color(0x0FFFFFFF),
            offset: Offset(0, 2),
            blurRadius: 4,
            blurStyle: BlurStyle.inner,
          ),
          BoxShadow(
            color: Color(0x14FFFFFF),
            offset: Offset(0, -2),
            blurRadius: 4,
            blurStyle: BlurStyle.inner,
          ),
        ],
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        children: [
          _buildBottomIcon(Icons.camera_alt),
          _buildBottomIcon(Icons.photo_library),
          _buildBottomIcon(Icons.settings),
          _buildBottomIcon(Icons.cloud_upload),
          _buildBottomIcon(Icons.folder_open),
        ],
      ),
    );
  }

  /// 构建底部图标按钮
  Widget _buildBottomIcon(IconData icon) {
    return Container(
      width: 48,
      height: 48,
      decoration: BoxDecoration(
        color: Colors.transparent,
        borderRadius: BorderRadius.circular(24),
      ),
      child: Icon(
        icon,
        size: 24,
        color: AppColors.textSecondary,
      ),
    );
  }
}
